
const userModel = appRequire('models/user');
var sha1 = require("sha1"); //引入加密模块
var util = require("util");
var menu = require("./menu");
var config = require("./config");
var common = require("./common");
const request = require("request");
var WechatAPI = require('wechat-api');

const commonModel = appRequire('models/common');
//var path = require("path");

let token = config.token;
let appID = config.appID;
let appScrect = config.appScrect;
let prefix = config.prefix;
let diyApi = config.diyApi;

// 暴露WeChat对象
module.exports = {
    webAuth,
    auth,
    getAccessToken,
    getConfigData
};

// 微信授权验证方法1
async function webAuth(req, request) {
    let postData = req.body;
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    requestGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + config.appID + "&secret=" + config.appScrect + "&code=" + postData.code + "&grant_type=authorization_code").then(async function (data) {
        console.log(data)
        let result = JSON.parse(data);
        if (result.openid) returnData.data = result.openid
        else {
            returnData.code = 0
            returnData.data = data
        }
        request.json(returnData)
    })
}

// 微信授权验证方法
async function auth(req, res) {
    getAccessToken().then(function (data) {
        var url = util.format(diyApi.createMenu, prefix, data);
        common.requestPost(url, JSON.stringify(menu)).then(function (data) {
            //将结果打印
            console.log(data);
        });
    });

    if (req.method == "GET") {
        // 获取微信服务器发送的数据
        let signature = req.query.signature
        let timestamp = req.query.timestamp
        let nonce = req.query.nonce
        let echostr = req.query.echostr

        // token、timestamp、nonce三个参数进行字典序排序
        var arr = [token, timestamp, nonce].sort().join('');
        // sha1加密    
        var result = sha1(arr);

        if (result === signature) {
            //autoMsg(req, res);
            res.send(echostr);
        } else {
            res.send('mismatch');
        }
    } else {
        autoMsg(req, res)
    }

}

// 获取全局票据
function getAccessToken() {
    return new Promise(async function (resolve, reject) {
        let accessTokenJson = await commonModel.commonToken.findOne({
            where: { type: "wxFWH" }
        })
        accessTokenJson = Common.clone(accessTokenJson);
        //console.log(accessTokenJson)
        var currentTime = new Date().getTime();

        //格式化请求地址,把刚才的%s按顺序替换
        var url = util.format(diyApi.getAccessToken, prefix, appID, appScrect);
        //判断本地存储的 access_token 是否有效
        //console.log(currentTime, accessTokenJson.expires_time, accessTokenJson.access_token)

        if (accessTokenJson == null || accessTokenJson.token === null || accessTokenJson.token === "" || accessTokenJson.expires_time < currentTime) {
            common.requestGet(url).then(async function (data) {
                var result = JSON.parse(data);
                console.log(result, accessTokenJson)
                //accessTokenJson.token = result.access_token;
                //accessTokenJson.expires_time = new Date().getTime() + (parseInt(result.expires_in) - 3600) * 1000;
                //更新本地存储的
                /*fs.writeFile('./controllers/wxFWH/access_token.json', JSON.stringify(accessTokenJson), err => {
                    resolve(result.access_token);
                });*/
                if (accessTokenJson) {
                    await commonModel.commonToken.update({
                        token: result.access_token,
                        expires_time: new Date().getTime() + (parseInt(result.expires_in) - 3600) * 1000
                    }, {
                        where: { type: "wxFWH" }
                    })

                } else {
                    await commonModel.commonToken.create({
                        objectId: sid.uuid(),
                        token: result.access_token,
                        expires_time: new Date().getTime() + (parseInt(result.expires_in) - 3600) * 1000,
                        type: "wxFWH"
                    })
                }

            });
        } else {
            //将本地存储的 access_token 返回
            resolve(accessTokenJson.token);
        }
    });
}

function getTicket(access_token) {
    const base = {
        appid: appID,//公众号appid
        secret: appScrect, // 公众号secret （重要不要暴露在前端）
        wxapi: "https://api.weixin.qq.com/cgi-bin"
    };
    return new Promise((resolve, reject) => {
        request.get(`${base.wxapi}/ticket/getticket?access_token=${access_token}&type=jsapi`, function (error, response, body) {
            if (error !== null) {
                reject("获取api_ticket失败 检查getTicket函数");
            }
            resolve(JSON.parse(body));
        });
    });
}


async function getConfigData(req, request) {
    let postData = req.body;
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    var api = new WechatAPI(appID, appScrect)
    var param = {
        debug: true,
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'editAddress', 'chooseImage',
            'onMenuShareAppMessage', 'onMenuShareTimeline', 'chooseImage', 'previewImage', 'uploadImage',
            'downloadImage', 'chooseWXPay'
        ],
        url: postData.url
    };
    api.getJsConfig(param, function (callback, result) {
        console.log(callback, result)
        returnData.data = result
        return request.json(returnData)
    });
}

// 封装一个get请求方法
async function requestGet(url) {
    return new Promise(function (resolve, reject) {
        request(url, (error, response, body) => {
            resolve(body);
        })
    })
}